<?php

namespace App\Http\Controllers\Front;

use App\Models\Notice;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\User;
use App\Http\Controllers\Controller;
use App\Interfaces\OrderService;
use App\Interfaces\OrderGoodsService;
use App\Interfaces\CartService;
use Session,Auth,Input;

class MyOrderController extends Controller
{

    /**
     * 我的订单列表
     * @param array $condations
     * @date 2016/01/08
     * @return mixed
     */
    public function index(Request $request)
    {

        $user = Auth::user();
        $page_size=10;
        //$status=$request->has('status')?$request->get('status'): "all";


        $query = Order::select('order.*','user.user_name','order_goods.comment_status','order_goods.goods_id')
            ->join('user','order.user_id','=','user.id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->where('order.user_id',$user->id);

        $filter = [
            'order_status' => $request->get('order_status'),
            'comment_status'=>$request->get('comment_status'),
            'date' => $request->get('date'),
        ];
        //按订单状态筛选
        if($filter['order_status']&&$filter['order_status']!='all'){
            $query = $query->where('order.order_status',$filter['order_status']);
            //dd($query->get());
        }

        //按订单评论状态筛选
        if(isset($filter['comment_status'])&&$filter['comment_status']=='0'){
            //dd(intval($filter['comment_status']));
            $query = $query->where('order.order_status',4)->where('order_goods.comment_status','=',intval( $filter['comment_status']));
            //dd($query->get());
        }

        //按订单时间筛选
        //$filter['date'] 1：近三个月；2：近一年；3：当年；4：去年；5：去年以前
        if($filter['date']&&$filter['date']=='1'){
            $query = $query->where('order.add_time','>',date('Y-m-d H:i:s',strtotime('-3 month')));
            //dd($query->get());
        }

        if($filter['date']&&$filter['date']=='2'){
            $query = $query->where('order.add_time','>',date('Y-m-d H:i:s',strtotime('-6 month')));
        }

        if($filter['date']&&$filter['date']=='3'){
            $date = date("Y",strtotime(date('Y-m-d',time())));
            $query = $query->whereRaw('year(order.add_time)= '.$date);
        }
        if($filter['date']&&$filter['date']=='4'){
            $date = date("Y",strtotime(date('Y-m-d',time())))-1;
            $query = $query->whereRaw('year(order.add_time)= '.$date);
        }
        if($filter['date']&&$filter['date']=='5'){
            $date = date("Y",strtotime(date('Y-m-d',time())))-1;
            $query = $query->whereRaw('year(order.add_time)< '.$date);
        }
        
        $query = $query->groupBy('order_goods.order_id')->orderBy('order.add_time','desc')->paginate($page_size);
        return view('front.my.order',compact('user','status','page_size','query','filter'));
    }

    /**
     * 下单页面（订单确认页面）
     *
     * @param array $goods
     * @return mixed
     *
     * @date 2016/01/08
     * @author Leen
     *
     */
    public function placeAnOrder(OrderService $orderService){

        //模拟数据
        $goods[0]['goods_id'] = 19;
        $goods[0]['goods_num'] = 1;
        $goods[1]['goods_id'] = 24;
        $goods[1]['goods_num'] = 1;
        $goods[1]['goods_id'] = 20;
        $goods[1]['goods_num'] = 1;

        //验证商品数据
        $orderService->validateGoods($goods);

        return view('front.my.place_an_order', compact('goods'));

    }//end func placeAnOrder()


    /**
     * 创建订单
     * @param array $goods
     * @date 2016/01/07
     * @return mixed
     */
    public function createOrder($user_id, Array $goods, $address_id, $express_id, $delivery_time, $pay_type, Array $invoiceInfo = [], $order_message = '', OrderService $orderService){

        $goods[0]['goods_id'] = 19;
        $goods[0]['goods_num'] = 1;
        $goods[1]['goods_id'] = 24;
        $goods[1]['goods_num'] = 1;
        /*$goods[2]['goods_id'] = 20;
        $goods[2]['goods_num'] = 1;*/

        $invoiceInfo = [];
        //$invoiceInfo['invoice'] = 1;                    //是否需要发票，0:不需要;1:需要
        $invoiceInfo['invoice_type'] = 0;               //发票类型，0:普通发票;
        $invoiceInfo['invoice_title_type'] = 0;         //发票抬头类型，0:个人;1:单位
        $invoiceInfo['invoice_title_content'] = '发票抬头内容';      //发票抬头内容

        $user_id = 1;
        $address_id = 38;
        $express_id = 1;
        $express_time = 1;
        $pay_type = 0;

        $orderService->createOrder($user_id, $goods, $address_id, $express_id, $express_time, $pay_type, $invoiceInfo, $order_message = '');
        dd('stop');
    }//end func createOrder

    /**
     * 展示
     * @param array $goods
     * @date 2016/01/07
     * @return mixed
     */
    public function show($order_id,OrderService $orderService){
        $order = $orderService->getByOrderId($order_id);
        $user = Auth::user();
        $notice = Notice::where('notice_id',$order_id)->first();
        $shopGoods = 0;
        $buyGoods = 0;
        $address_id = 0;
        //$orderService->calculateOrderGoods($shopGoods,$buyGoods,$address_id);
        return view('front.my.order_detail',compact('order','user','notice'));

    }//end func

    public function search(OrderService $orderService){
        $key = trim(Input::get('key'));
        $order = $orderService->getByOrderSn($key, Auth::user()->id);
        if($order){
            return response()->json(['status'=>1,'order_id'=>$order->order_id]);
            //return view('front.my.order_detail',compact('order'));
        }else{
            return response()->json(['status'=>0,'message'=>'该订单不存在！']);
            //return redirect()->back()->withInput()->withMessage('该订单不存在！');
        }

    }

    public function destroy($order_id,Request $request)
    {
        $order_id = $request->order_id;
        $order = Order::find($order_id);
        
        if($order->order_status==4||$order->order_status==5){
            $status = $order->delete();
            return response()->json(['status'=>$status]);
        }else{
            return response()->json(['status'=>0,'message'=>'只有已完成和已取消的订单可以删除！']);
        }

    }
//    public function combinePayOrder(OrderService $orderService,Request $request){
//        $user_id =  Auth::user()->id;
//        $order_ids = $request->orderIdArr;
//        $orderIdArr = explode(",",$order_ids);
//        $orderPayId = $orderService->combinePay($user_id,$orderIdArr);
//        return response()->json(['orderPayId'=>$orderPayId]);
//
//    }
//    public function payOrder(OrderService $orderService,Request $request){
//        $user_id =  Auth::user()->id;
//        $order_ids = $request->order_id;
//        $orderIdArr=array();
//        $orderIdArr[0] = $order_ids;
//        $orderPayId = $orderService->combinePay($user_id,$orderIdArr);
//        return response()->json(['orderPayId'=>$orderPayId]);

//    }
    public function cancelOrder(OrderService $orderService,Request $request){
        $order_id = $request->order_id;
        $reason = $request->reason;

        $user_id =  Auth::user()->id;
        $cancelOrder = $orderService->cancel($order_id,$reason,$user_id);
        return response()->json(['status'=>$cancelOrder]);

    }
    public function receiveGoods(OrderService $orderService,Request $request){
        $order_id = $request->order_id;
        $order = $orderService->reciveGoods($order_id);
        return response()->json(['status'=>$order]);

    }

    public function remind(Request $request,Notice $notice){

        $param = $request->all();
        $param['notice_type'] = "订单发货";
        $param['notice_time'] = date('Y-m-d H:i:s');
        $notice = $notice->create($param);
        return response()->json(['status'=>$notice->id]);

    }

    public function payagain(Request $request,OrderGoodsService $orderGoodsService, CartService $cartService)
    {
        $orderGoods = $orderGoodsService->getOrderGoodsById($request->get('order_id'));
        $return = ['message'=>''];
        foreach($orderGoods as $key=>$goods){
            $goods_id = $goods['goods_id'];
            $goods_num = $goods['buy_number'];
            if(empty($goods_id)){
                $return['message'] = '商品id不能为空';
            }
            if(empty($goods_num)){
                $return['message'] = '商品数量不能为空';
                $return['message'] = '商品数量不能为空';
            }
            try{
                $cartService->addGoods($goods_id,$goods_num);
                $cartNum=$cartService->getCartNumber();
                $return['goods_num'] = $cartNum;
            } catch (InvalidArgumentException $e) {
                $return['message'] = $e->getMessage();
            }//end try
        }//end foreach

        //dd($goods['goods_id']);
        return Response()->json($return);
    }//end func payagain



}//end class
